﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class TestYield : MonoBehaviour
{
    IEnumerator currentMoveCoroutine;
    public Transform[] path;
    void Start()
    {
        
        string[] messages = { "welcome", "hello", "you" };
        StartCoroutine(PrintMessage(messages, 1f));
        StartCoroutine(FollowPath());
        
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))    
        {
            if (currentMoveCoroutine != null)   
            {
                StopCoroutine(currentMoveCoroutine);
            }
            currentMoveCoroutine = Move(Random.onUnitSphere * 5, 8f);
            StartCoroutine(currentMoveCoroutine);
        }
    }

    IEnumerator Move(Vector3 destination,float speed)  
    {
        while (transform.position != destination)   
        {
            transform.position = Vector3.MoveTowards(transform.position, destination, speed * Time.deltaTime);
            yield return null;
        }
    }

    IEnumerator FollowPath() 
    {
        foreach (Transform waypoint in path) 
        {
            yield return StartCoroutine(Move(waypoint.position, 8f));
            
        }
    }

    IEnumerator PrintMessage(string[] messages, float delay)  
    {
        foreach (string msg in messages)
        {
            print (msg);
            yield return new WaitForSeconds(delay);
        }
    }

    
}
